package com.common.utils.executorsutils.pool;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 库存实例-
 * 使用懒汉模式双重校验模式
 *
 */
public class Store {

    //初始库存数量
    private static AtomicInteger count = new AtomicInteger(1000000);

    private static AtomicInteger kjcount = new AtomicInteger(0);

    private static Store store;

    public int getCount() {
        return count.get();
    }

    public int getKjcount() {
        return kjcount.get();
    }

    public Store(){

    }

    //懒汉单例模式双重校验
    public static synchronized Store getInstance() {
       if (store == null) {
            synchronized (Store.class) {
                if(store == null){
                    store = new Store();
                }
            }
        }
        return store;
    }

    //扣减库存操作
    public synchronized boolean increment(int randomNumber) {
        int currentStock = count.get();
        if (currentStock > randomNumber){
            int newStock = count.get() - randomNumber;
            if(count.compareAndSet(currentStock, newStock)){
                System.out.println("本次扣减的库存是：" +randomNumber);
                kjcount.set(kjcount.get()+randomNumber);
                return true;
            }
        }
        return false;
    }
}
